package com.zz.springboot.service.impl;

import com.zz.springboot.dto.RoleDto;
import com.zz.springboot.dto.UserDto;
import com.zz.springboot.enums.RolesEnum;
import com.zz.springboot.exception.BizException;
import com.zz.springboot.manager.UserManager;
import com.zz.springboot.resp.enums.RespCodeEnum;
import com.zz.springboot.service.UserService;
import com.zz.springboot.util.PasswordUtils;
import com.zz.springboot.util.SnowFlake;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    UserManager userManager;

    @Override
    @Transactional
    public void register(String username, String password) {
        // 对密码进行加密
        String encodedPassword = PasswordUtils.encryptPassword(password, username);
        // 插入用户数据
        // 创建雪花算法实例
        SnowFlake snowflake = new SnowFlake(1, 1);
        // 生成唯一的 ID
        Long userId = snowflake.nextId();
        userManager.insertUserData(userId, username, encodedPassword);
        // 插入用户角色（注册时默分配普通用户角色）
        RoleDto role = userManager.selectRoleByRoleCode(RolesEnum.USER.getCode());
        userManager.insertUserRoleData(userId, role.getId());
        // 插入有效天数
        userManager.insertUserValidDays(username, 3);

    }

    @Override
    public boolean verifyOnlyUsername(String username) {
        return userManager.verifyOnlyUsername(username);
    }

    @Override
    public UserDto selectUserByUsername(String username) {
        return userManager.selectUserByUsername(username);
    }

    @Override
    public Integer selectUserValidDaysByUsername(String username) {
        return userManager.selectUserValidDaysByUsername(username);
    }

    @Override
    public void setUserValidDays(String username, Integer validDays) {
        //先查看用户是否存在
        if (verifyOnlyUsername(username)) {
            throw new BizException(RespCodeEnum.USER_NOT_EXISTS);
        }
        userManager.updateUserValidDays(username, validDays);
    }
}
